package example.lec02;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.lang.reflect.Method;

public class TestMain {
    public static void test0() throws Exception
    {
        //java 反射机制
        Class<?> cls= Class.forName("example.lec02.ExampleBean");
        System.out.println("Class represented by myClass: " + cls.toString());
        //调用类的构造器创建对象obj (也就是 bean)
        Object obj = cls.newInstance();
        //查找setIntValue()方法
        String set_tag = "set";
        String get_tag = "get";
        Method setMethod= cls.getMethod(set_tag+"IntValue", int.class);
        setMethod.invoke(obj, 12345); //调用bean实例的setIntValue()方法
        Method getMethod = cls.getMethod(get_tag+"IntValue");
        System.out.println(getMethod.invoke(obj));

        setMethod= cls.getMethod(set_tag+"DoubleValue", double.class);
        setMethod.invoke(obj, 1.2345); //调用bean实例的setIntValue()方法
        getMethod = cls.getMethod(get_tag+"DoubleValue");
        System.out.println(getMethod.invoke(obj));

    }
    public static void test1() throws InterruptedException
    {
        
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean_lec02.xml");
        
        String[] li = {"p1", "pp2"};
        // bean的默认scope 是 Singleton
        // bean 和 component的区别

        for (String s : li) {
            Person p1 = (Person)ctx.getBean(s);
            Person p2 = (Person)ctx.getBean(s);
            System.out.println(s+"\t"+(p1 == p2));
        }

        java.util.Date d1 = (java.util.Date)ctx.getBean("date_proto");
        Thread.sleep(1000);
        java.util.Date d2 = (java.util.Date)ctx.getBean("date_proto");
        System.out.println(d1);
        System.out.println(d2);

    }

    public static void test2()
    {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean_lec02.xml");
        ExampleBean eb = (ExampleBean)ctx.getBean("eb1");
        System.out.println(eb.getIntValue());
        System.out.println(eb.getDoubleValue());
    }

    public static void test3()
    {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean_lec02.xml");
        Person p = (Person)ctx.getBean("p4");
        System.out.println(p.toString());
    }

    public static void test4()
    {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean_lec02.xml");
        Student s = (Student)ctx.getBean("s1", Student.class);
        System.out.println(s.toString());
    }

    public static void main(String[] args) throws Exception
    {
        test0();
        test1();
        test2();
        test3();
        test4();
    }
}
